var db = require('bookshelf').bookshelf;
var Database = require('../app/database');
var moment = require('moment');
var util = require('util');
var ServerController = module.exports = {};

log = function(msg) {
    //console.log(new Date().toLocaleTimeString() + ' [config_controller]: ' + msg);
};

ServerController.initialize = function(router) {
	log('initialize: ' + util.inspect(router,false,null));
	router
    .add({Method: router.Methods.GET, URL: 'servers', Authorize: router.Access.User, Handler: ServerController.getServers})
	.add({Method: router.Methods.GET, URL: 'servers/templates', Authorize: router.Access.User, Handler: ServerController.getServersWithTemplates})
	.add({Method: router.Methods.GET, URL: 'servers/:id/configs', Authorize: router.Access.User, Handler: ServerController.getServerWithConfigs})
	.add({Method: router.Methods.GET, URL: 'servers/:id/templates', Authorize: router.Access.User, Handler: ServerController.getServerWithTemplates})
	.add({Method: router.Methods.GET, URL: 'servers/:id', Authorize: router.Access.User, Handler: ServerController.getServer})
	.add({Method: router.Methods.POST, URL: 'servers', Authorize: router.Access.Admin, Handler: ServerController.postServer})
	.add({Method: router.Methods.POST, URL: 'servers/:id/actions', Authorize: router.Access.User, Handler: ServerController.postServerAction})
};

ServerController.getServers = function(req, res) {
	log('getServers: ' + req.originalUrl);
	new Database.Collections.Servers()
		.fetch()
		.then(function(resp) {
			res.json(200, resp);
			log('replied: ' + util.inspect(resp,false,null));
		});
};

ServerController.getServer = function(req, res) {
	log('getServer: ' + req.originalUrl);	
	new Database.Models.Server({server_id: req.params.id})
		.fetch()
		.then(function(resp) {
			if (!resp) {
			    res.json(404, { status: 404, type: 'Resource', message: 'Not found' });
			} else {
				res.json(200, resp);
			};
			log('replied: ' + util.inspect(resp,false,null));
		});
};
ServerController.getServerWithConfigs = function(req, res) {
	log('getServerWithConfigs: ' + req.originalUrl);	
	new Database.Models.Server({server_id: req.params.id})
		.fetch({withRelated: ['configs']})
		.then(function(resp) {
			if (!resp) {
			    res.json(404, { status: 404, type: 'Resource', message: 'Not found' });
			} else {
				res.json(200, resp);
			};
			log('replied: ' + util.inspect(resp,false,null));
		});
};
ServerController.getServerWithTemplates = function(req, res) {
	log('getServerWithTemplates: ' + req.originalUrl);	
	new Database.Models.Server({server_id: req.params.id})
		.fetch({withRelated: ['templates']})
		.then(function(resp) {
			if (!resp) {
			    res.json(404, { status: 404, type: 'Resource', message: 'Not found' });
			} else {
				res.json(200, resp);
			};
			log('replied: ' + util.inspect(resp,false,null));
		});
};

ServerController.getServersWithTemplates = function(req, res) {
	log('getServersWithTemplates: ' + req.originalUrl);
	new Database.Collections.Servers()
		.fetch({withRelated: ['templates']})
		.then(function(resp) {
			res.json(200, resp);
			log('replied: ' + util.inspect(resp,false,null));
		});
};

ServerController.postServer = function(req, res) {
	log('postServer: ' + req.originalUrl + ' - ' + util.inspect(req.body,false,null));
	if (req.body) {
		if (req.body.name && req.body.name.length <= 0) {
			delete req.body.name;
		};
		if (req.body.server_id && req.body.server_id <= 0) {
			delete req.body.server_id;
		};
		if (req.body.last_datetime) {
			delete req.body.last_datetime;
		};
		if (!req.body.server_id && !req.body.name) {
			res.send(500,null);
		} else {
            new Database.Models.Server({server_id: req.body.server_id})
                .fetch()
                .then(function(resp){
                    if (resp != null) {
			            resp.set(req.body);
                        resp
				            .save()
				            .then(function(resp) {
					            res.json(200, resp);
					            log('replied: ' + util.inspect(resp,false,null));
				            });
                    } else {
                        res.send(500,null);
                    };
                });
		};
	} else {
	    res.send(500, { status: 500, type: 'Resource', message: 'Argument not valid' });
	};	
};
ServerController.postServerAction = function(req, res) {
	log('postServerAction: ' + req.originalUrl + ' - ' + util.inspect(req.body,false,null));
	if (req.body) {
		if (req.body.server_id && req.body.server_id <= 0) {
			delete req.body.server_id;
		};
		if (req.body.action && req.body.action.length <= 0) {
			delete req.body.action;
		};
		if (!req.body.server_id || !req.body.action) {
			res.send(500,{user:req.session.user});
		} else {
			req.body.user_id = req.session.user.user_id;
			new Database.Models.Action(req.body)
				.save()
				.then(function(resp) {
					log('saved: ' + util.inspect(resp, false, null));
                    var server = {server_id:resp.attributes.server_id, is_starting: 0, is_stopping: 0, is_updating: 0, last_datetime:moment().format(moment.application_dateformat)};
					switch(resp.attributes.action.toLowerCase())
					{
						case 'stop':
                            server.is_stopping = 1;
							break;
						case 'update':
                            server.is_updating = 1;
							break;
						default:
                            server.is_starting = 1;
                            break;
					};
                    new Database.Models.Server({server_id: server.server_id})
                        .fetch()
                        .then(function(resp){
                            if (resp != null) {
			                    resp.set(server);
                                resp
				                    .save()
				                    .then(function(resp) {
					                    res.json(200, resp);
					                    log('replied: ' + util.inspect(resp,false,null));
				                    });
                            } else {
                                res.send(500,null);
                            };
                        });
				});
		};
	} else {
	    res.send(500, { status: 500, type: 'Resource', message: 'Argument not valid' });
	};	
};